$(function(){
  var nameRx = /^locations\[(\d+)\]\[city\]$/;
  // find city inputs
  $('input[type="text"]').each(function() {
    var name = $(this).attr('name');
    var matches = nameRx.exec(name);
    if (matches) {
      var locationNo = matches[1];
      $(this).keyup(function() {
        var $input = $(this);
        var value = $(this).val();
        //Country selector has following classes: form-select location_auto_country location-processed
        var country = $(this).closest('div.fieldset-wrapper').find('select.location_auto_country:first option:selected').text();
        $.getJSON('https://maps-api-ssl.google.com/maps/suggest?callback=?', {
          q: country + ', ' +value
        }, function(data, status){
          var arr = new Array();
          if (data.suggestion) {
            for (var i = 0; i < data.suggestion.length; i++) {
              arr.push(data.suggestion[i].query);
            }
            $input.autocomplete(arr);
          }
        });
      });
    }
  });
});